<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!--添加角色区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" :stripe="true" border style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <!--作用域插槽-->
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bd-bottom', i1 === 0 ? 'bd-top' : '', 'vcenter']">
              <!-- 渲染一级 -->
              <el-col :span="6">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--  通过for循环, 嵌套渲染二级和三级权限 -->
              <el-col :span="18">
                <el-row v-for="(subItem, i2) in item1.children" :key="subItem.id" :class="[i2 === 0 ? '' : 'bd-top', 'vcenter']">
                  <!-- 渲染2级权限-->
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row, subItem.id)">{{ subItem.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="item3 in subItem.children" :key="item3.id" closable type="warning" @close="removeRightById(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="400px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-delete" @click="removeEditDialog(scope.row.id)">删除</el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="danger" size="mini" icon="el-icon-setting" @click="setRightsDialog(scope.row)">分配角色</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="34%" @close="addRolesDialogClose">
      <el-form ref="addFormRef" label-width="110px" :model="addForm" :rules="addFormRules">
        <!-- 添加角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <!-- 添加角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesRes">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="34%">
      <!-- 内容主体区域 -->
      <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="70px">
        <!-- prop=username 对应了 addFormRules中的username校验规则-->
        <el-form-item label="角色名称" label-width="85px" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="85px" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleRegin">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="34%" @close="setRightsDialogClosed">
      <!-- 树形结构展示 -->
      <el-tree ref="treeRef" :data="rightsList" :default-checked-keys="defKeys" :default-expand-all="true" :props="treeProps" node-key="id" show-checkbox></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 对话框显示与隐藏
      addRoleDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      // 所有角色列表数据
      rolesList: [],
      // 添加角色数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入添加角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [{ required: true, message: '请输入添加角色描述', trigger: 'blur' }]
      },
      // 当前查询角色id的数据
      editForm: {},
      // 所有权限的数据
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesinfo()
  },
  methods: {
    // 获取所有角色列表
    async getRolesinfo() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表数据失败')
      }
      this.rolesList = res.data
    },
    // 添加角色
    addRolesRes() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败！')
        }
        this.addRoleDialogVisible = false
        this.getRolesinfo()
        this.$message.success('添加角色成功')
      })
    },
    // 监听 添加角色对话框的关闭事件
    addRolesDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 展示编辑对话框
    async showEditDialog(roles) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`roles/${roles}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.editForm = res.data
    },
    // 编辑角色
    editRoleRegin() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return console.log('1')
        }
        const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户角色失败!')
        }
        // 关闭对话框
        this.editDialogVisible = false
        this.getRolesinfo()
        this.$message.success('更新用户角色成功')
      })
    },
    // 删除角色
    async removeEditDialog(roles) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete(`roles/${roles}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败!')
      }
      this.$message.success('删除成功')
      this.getRolesinfo()
    },
    // 获取权限管理分配角色
    async setRightsDialog(roles) {
      this.roleId = roles.id
      console.log()
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      this.getLeafKeys(roles, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式,获取角色所有三级权限的id
    getLeafKeys(nodes, arr) {
      if (!nodes.children) {
        return arr.push(nodes.id)
      }
      nodes.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框并重置defkwys数组的关闭事件
    setRightsDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.getRolesinfo()
      this.setRightDialogVisible = false
      this.$message.success('分配权限成功！')
    },
    // 根据id权限删除对应的权限
    async removeRightById(coles, colesId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${coles.id}/rights/${colesId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      coles.children = res.data
      this.$message.success('删除权限成功!')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bd-top {
  border-top: 1px solid #eee;
}

.bd-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
